package com.haifeng.lyw.jinganghc.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.haifeng.lyw.jinganghc.R;
import com.haifeng.lyw.jinganghc.activity.SetActivity;
import com.haifeng.lyw.jinganghc.dao.UserDao;
import com.haifeng.lyw.jinganghc.dao.UserInfo;
import com.haifeng.lyw.jinganghc.utils.HexUtil;
import com.haifeng.lyw.jinganghc.utils.NavController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class WorkView extends Activity implements View.OnTouchListener, View.OnClickListener, NavController.OnNavAndSpeedListener {


    private ImageView left_up, left_left, left_down, left_right, left_icon_up, left_icon_down, right_up, right_up2, right_up3, right_left,
            right_right, right_down, right_down2, right_down3, iv_custom1, iv_custom2, iv_custom3, iv_custom4, iv_custom5, work_qidong;
    private TextView work_set, work_state;
    private String code = "";
    private ToggleButton work_tog;
    private final String init_String = "#13*1300*60*3*4*200*120*450*145*600*170*720*200*3972$";
    private boolean reset;
    private List<UserInfo> lists = new ArrayList<>();
    private boolean isTouch;
    private int mNav;
    AssetFileDescriptor fileDescriptor;
    AudioManager mAudioManager;
    private MediaPlayer myMediaPlayer;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setView();
        connect();
        initMedia();
    }

    private void setView() {
        NavController navController = (NavController) findViewById(R.id.nav_control);
        navController.setOnNavAndSpeedListener(this);
        left_up = findViewById(R.id.left_up);
        left_up.setOnTouchListener(this);
        left_left = findViewById(R.id.left_left);
        left_left.setOnTouchListener(this);
        left_down = findViewById(R.id.left_down);
        left_down.setOnTouchListener(this);
        left_right = findViewById(R.id.left_right);
        left_right.setOnTouchListener(this);
        left_icon_up = findViewById(R.id.left_icon_up);
        left_icon_up.setOnTouchListener(this);
        left_icon_down = findViewById(R.id.left_icon_down);
        left_icon_down.setOnTouchListener(this);

        work_qidong = findViewById(R.id.work_qidong);
        work_qidong.setOnClickListener(this);
        right_up = findViewById(R.id.right_up);
        right_up.setOnClickListener(this);
        right_up2 = findViewById(R.id.right_up2);
        right_up2.setOnClickListener(this);
        right_up3 = findViewById(R.id.right_up3);
        right_up3.setOnClickListener(this);
        work_set = findViewById(R.id.work_set);
        work_set.setOnClickListener(this);
        work_state = findViewById(R.id.work_state);

        right_left = findViewById(R.id.right_left);
        right_left.setOnClickListener(this);
        right_right = findViewById(R.id.right_right);
        right_right.setOnClickListener(this);
        right_down = findViewById(R.id.right_down);
        right_down.setOnClickListener(this);
        right_down2 = findViewById(R.id.right_down2);
        right_down2.setOnClickListener(this);
        right_down3 = findViewById(R.id.right_down3);
        right_down3.setOnClickListener(this);
        work_tog = findViewById(R.id.work_tog);
        work_tog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    reset = true;
                    Log.e("WWDZ", "isChecked1" + isChecked);
                    right_up.setBackgroundResource(R.drawable.yd_zuoti);
                    right_up2.setBackgroundResource(R.drawable.yd_xiaoti);
                    right_up3.setBackgroundResource(R.drawable.yd_dati);
                    right_left.setBackgroundResource(R.drawable.yd_youti);
                    right_right.setBackgroundResource(R.drawable.yd_zuodang);
                    right_down.setBackgroundResource(R.drawable.yd_qiandao);
                    right_down2.setBackgroundResource(R.drawable.yd_houdao);
                    right_down3.setBackgroundResource(R.drawable.yd_youdang);

                } else {
                    reset = false;
                    Log.e("WWDZ", "isChecked2" + isChecked);
                    right_up.setBackgroundResource(R.drawable.gd_zuozhang);
                    right_up2.setBackgroundResource(R.drawable.gd_zuoquan);
                    right_up3.setBackgroundResource(R.drawable.gd_youquan);
                    right_left.setBackgroundResource(R.drawable.gd_youzhang);
                    right_right.setBackgroundResource(R.drawable.gd_zuotui);
                    right_down.setBackgroundResource(R.drawable.gd_qianfan);
                    right_down2.setBackgroundResource(R.drawable.gd_houfan);
                    right_down3.setBackgroundResource(R.drawable.gd_youtui);
                }
            }
        });

        iv_custom1 = findViewById(R.id.iv_custom1);
        iv_custom1.setOnClickListener(this);
        iv_custom2 = findViewById(R.id.iv_custom2);
        iv_custom2.setOnClickListener(this);
        iv_custom3 = findViewById(R.id.iv_custom3);
        iv_custom3.setOnClickListener(this);
        iv_custom4 = findViewById(R.id.iv_custom4);
        iv_custom4.setOnClickListener(this);
        iv_custom5 = findViewById(R.id.iv_custom5);
        iv_custom5.setOnClickListener(this);
    }
    private void  initMedia() {
        /**
         * 把音乐音量强制设置为最大音量
         */
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); // 获取当前音乐音量
        int maxVolume = mAudioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);// 获取最大声音
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 5, 0); // 设置为最大声音，可通过SeekBar更改音量大小
        myMediaPlayer = new MediaPlayer();
        try {
            fileDescriptor = WorkView.this.getAssets().openFd("wq.mp3");

            myMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            myMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),

                    fileDescriptor.getStartOffset(),

                    fileDescriptor.getLength());

            myMediaPlayer.prepare();
            myMediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 将数据分包
     **/
    public int[] dataSeparate(int len) {
        int[] lens = new int[2];
        lens[0] = len / 20;
        lens[1] = len - 20 * lens[0];
        return lens;
    }

    //打包要发送的数据
    public byte[] getSendDate(String code) {


        byte[] buff = code.getBytes();
        int len = buff.length;
        int[] lens = dataSeparate(len);

        return buff;
    }


    private void connect() {

        for (int i = 0; i < Common.bleAddrList.size(); i++) {
            Common.bleAddrList.get(i).connectGatt(this, false, coreGattCallback);

        }

        Log.i("WWDZ", "connect22");

    }

    /**
     * 蓝牙所有相关操作的核心回调类
     */
    private BluetoothGattCallback coreGattCallback = new BluetoothGattCallback() {

        /**
         * 连接状态改变，主要用来分析设备的连接与断开
         * @param gatt GATT
         * @param status 改变前状态
         * @param newState 改变后状态
         */
        @Override
        public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
            Log.e("WWDZ", "onConnectionStateChange  status: " + status + " ,newState: " + newState +
                    "  ,thread: " + Thread.currentThread().getId());
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                gatt.discoverServices();
                Log.e("WWDZ", "连接成功");
            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                Log.e("WWDZ", "连接失败");
                Log.i("WWDZ", "newState==" + newState);
            } else if (newState == BluetoothGatt.STATE_CONNECTING) {
                Log.e("WWDZ", "连接成功2");
            }
        }

        /**
         * 发现服务，主要用来获取设备支持的服务列表
         * @param gatt GATT
         * @param status 当前状态
         */
        @Override
        public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
            Log.e("WWDZ", "服务" + "status:" + status);
            if (status == 0) {

                Common.bluetoothGattList.add(gatt);
                Log.e("WWDZ", "发现服务成功" + "status:" + status);
//if(Common.bluetoothGattList=Common.bluetoothGattList.get(Common.bluetoothGattList.size()-1)){
//
//}

            } else {
                Log.e("WWDZ", "发现服务失败");
            }
        }

        /**
         * 读取特征值，主要用来读取该特征值包含的可读信息
         * @param gatt GATT
         * @param characteristic 特征值
         * @param status 当前状态
         */
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
            Log.e("WWDZ", "onCharacteristicRead  status: " + status + ", data:" + HexUtil.encodeHexStr(characteristic.getValue()));
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e("WWDZ", "读取特征值成功");
            } else {
                Log.e("WWDZ", "读取特征值失败");
            }
        }

        /**
         * 写入特征值，主要用来发送数据到设备
         * @param gatt GATT
         * @param characteristic 特征值
         * @param status 当前状态
         */
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
            Log.e("WWDZ", "onCharacteristicWrite  status: " + status + ", data:" + HexUtil.encodeHexStr(characteristic.getValue()));
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e("WWDZ", "发送成功");
            } else {
                Log.e("WWDZ", "发送失败");
            }
        }

        /**
         * 特征值改变，主要用来接收设备返回的数据信息
         * @param gatt GATT
         * @param characteristic 特征值
         */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
            Log.e("WWDZ", "onCharacteristicChanged data:" + HexUtil.encodeHexStr(characteristic.getValue()));
        }

        /**
         * 读取属性描述值，主要用来获取设备当前属性描述的值
         * @param gatt GATT
         * @param descriptor 属性描述
         * @param status 当前状态
         */
        @Override
        public void onDescriptorRead(BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) {
            Log.e("WWDZ", "onDescriptorRead  status: " + status + ", data:" + HexUtil.encodeHexStr(descriptor.getValue()));
        }

        /**
         * 写入属性描述值，主要用来根据当前属性描述值写入数据到设备
         * @param gatt GATT
         * @param descriptor 属性描述值
         * @param status 当前状态
         */
        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) {
            Log.e("WWDZ", "onDescriptorWrite  status: " + status + ", data:" + HexUtil.encodeHexStr(descriptor.getValue()));
        }

        /**
         * 阅读设备信号值
         * @param gatt GATT
         * @param rssi 设备当前信号
         * @param status 当前状态
         */
        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, final int rssi, final int status) {
            Log.e("WWDZ", "onReadRemoteRssi  status: " + status + ", rssi:" + rssi);
        }
    };

    private void send(String order) {
        try {


            for (int i = 0; i < Common.bleAddrList.size(); i++) {


                List<List<BluetoothGattCharacteristic>> chats = displayGattServices(Common.bluetoothGattList.get(i).getServices(), i);

                Common.mCharacteristic.get(i).setValue(order);
                Common.bluetoothGattList.get(i).writeCharacteristic(Common.mCharacteristic.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(WorkView.this, "部分设备未发送成功！", Toast.LENGTH_SHORT).show();
        }
        ;

    }

    private List<List<BluetoothGattCharacteristic>> displayGattServices(final List<BluetoothGattService> gattServices, int i) {
        if (gattServices == null) return null;

        List<List<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<>();

        for (final BluetoothGattService gattService : gattServices) {
//            Log.e(TAG, "group : " + gattService.getUuid().toString());
            List<BluetoothGattCharacteristic> charas = new ArrayList<>();

            List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();

            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
//                Log.e(TAG, "item   : " + gattCharacteristic.getUuid().toString());
                mGattCharacteristics.add(charas);
                if (gattCharacteristic.getUuid().toString().equals("0000ffe1-0000-1000-8000-00805f9b34fb")) {

                    Common.mCharacteristic.add(gattCharacteristic);
                    //= gattCharacteristic;

                }

            }
        }

        return mGattCharacteristics;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.e("WWDZ", "按钮按下");
                sendOrder(view.getId(), true);
                break;
            case MotionEvent.ACTION_UP:
                Log.e("WWDZ", "按钮抬起");
                sendOrder(view.getId(), false);
                myHandler.removeMessages(2);
                break;
        }
        return false;
    }


    /**
     * 发送指令
     *
     * @param id     按钮
     * @param action true 按下；false 抬起
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void sendOrder(int id, boolean action) {

        if (!reset) {
            if (!isTouch) {
                isTouch = true;
                switch (id) {
                    case R.id.left_up://中向上

                        code = "g";

                        break;
                    case R.id.left_down://中向下

                        code = "Z";

                        break;
                    case R.id.left_left://中向左

                        code = "f";

                        break;
                    case R.id.left_right://中向右

                        code = "e";

                        break;
                    case R.id.left_icon_up:

                        code = "b";

                        break;
                    case R.id.left_icon_down:

                        code = "a";

                        break;
                }
            }
        } else {
            if (!isTouch) {
                isTouch = true;
                switch (id) {
                    case R.id.left_up://中向上

                        code = "g";

                        break;
                    case R.id.left_down://中向下

                        code = "Z";

                        break;
                    case R.id.left_left://中向左

                        code = "f";

                        break;
                    case R.id.left_right://中向右

                        code = "e";

                        break;
                    case R.id.left_icon_up:

                        code = "b";

                        break;
                    case R.id.left_icon_down:

                        code = "a";

                        break;
                }
            }
        }
        if (action) {
            myHandler.sendEmptyMessage(2);

        } else {
            myHandler.sendEmptyMessage(3);

        }

    }

    private Handler myHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Log.e("WWDZ", "无 " + code);
                    break;
                case 2:

                    if (isTouch) {
                        if (!TextUtils.isEmpty(code))

                            send(code);
                        //	sendByBle(code);
                        myHandler.sendEmptyMessageDelayed(2, 200);

                    }
                    //  myHandler.sendEmptyMessage(2);
                    break;
                case 3:


                    if (!TextUtils.isEmpty(code))
                        //	sendByBle(code);
                        myHandler.removeMessages(2);
                    //	code = "";
                    isTouch = false;
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @Override
    public void onClick(View v) {
        if (!reset) {
            switch (v.getId()) {
                case R.id.work_set:
                    Intent toSet = new Intent(WorkView.this, SetActivity.class);
                    startActivity(toSet);
                    break;
                case R.id.right_up:
                    send("N");
                    break;
                case R.id.right_up2:
                    send("V");
                    break;
                case R.id.right_up3:
                    send("T");
                    break;
                case R.id.right_left:
                    send("L");
                    break;
                case R.id.right_right:
                    send("n");
                    break;
                case R.id.right_down:
                    send("S");
                    break;
                case R.id.right_down2:
                    send("U");
                    break;
                case R.id.right_down3:
                    send("l");
                    break;
                case R.id.work_qidong:
                    send("y");//开始
                    break;
                /**
                 * 自定义键
                 */
                case R.id.iv_custom1:
                    queryListData(0);

                    break;
                case R.id.iv_custom2:
                    queryListData(1);

                    break;
                case R.id.iv_custom3:
                    queryListData(2);

                    break;
                case R.id.iv_custom4:
                    queryListData(3);

                    break;
                case R.id.iv_custom5:
                    queryListData(4);

                    break;


            }
        } else {
            switch (v.getId()) {
                case R.id.work_set:
                    Intent toSet = new Intent(WorkView.this, SetActivity.class);
                    startActivity(toSet);
                    break;
                case R.id.right_up:
                    send("v");
                    break;
                case R.id.right_up2:
                    send("r");
                    break;
                case R.id.right_up3:
                    send("t");
                    break;
                case R.id.right_left:
                    send("p");
                    break;
                case R.id.right_right:
                    send("T");
                    break;
                case R.id.right_down:
                    send("o");
                    break;
                case R.id.right_down2:
                    send("O");
                    break;
                case R.id.right_down3:
                    send("V");
                    break;
                case R.id.work_qidong:
                    send("y");//开始
                    break;
                /**
                 * 自定义键
                 */
                case R.id.iv_custom1:
                    queryListData(0);

                    break;
                case R.id.iv_custom2:
                    queryListData(1);

                    break;
                case R.id.iv_custom3:
                    queryListData(2);

                    break;
                case R.id.iv_custom4:
                    queryListData(3);

                    break;
                case R.id.iv_custom5:
                    queryListData(4);

                    break;
            }
        }
    }

    /**
     * 查询数据
     */
    private void queryListData(int pos) {
        lists = UserDao.getInstance().queryAllData();
        if (lists != null) {
            String action_order = lists.get(pos).getAction_order();
            Log.i("WWDZ", "action_order===" + action_order);
            send(action_order);
        } else {
            Toast.makeText(WorkView.this, "您还没有添加自定义动作！", Toast.LENGTH_SHORT).show();
        }


    }

    public static String bytesToHexString(byte[] bytes) {
        String result = "";
        for (int i = 0; i < bytes.length; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            result += hexString.toUpperCase();
        }
        return result;
    }

    private byte[] getHexBytes(String message) {
        int len = message.length() / 2;
        char[] chars = message.toCharArray();
        String[] hexStr = new String[len];
        byte[] bytes = new byte[len];
        for (int i = 0, j = 0; j < len; i += 2, j++) {
            hexStr[j] = "" + chars[i] + chars[i + 1];
            bytes[j] = (byte) Integer.parseInt(hexStr[j], 16);
        }
        return bytes;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!myMediaPlayer.isPlaying()){
            try {
                myMediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myMediaPlayer.start();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        myMediaPlayer.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onNavAndSpeed(int nav) {
        if (mNav != nav) {
            isTouch = false;
            myHandler.removeMessages(2);
        }
        if (!isTouch) {

            isTouch = true;
            mNav = nav;
            if (nav == 5) {
                code = "G";//右
                myHandler.sendEmptyMessage(2);
            } else if (nav == 3) {
                code = "h";//下
                myHandler.sendEmptyMessage(2);
            } else if (nav == 7) {
                code = "d";//上
                myHandler.sendEmptyMessage(2);
            } else if (nav == 1) {
                code = "D";//左
                myHandler.sendEmptyMessage(2);
            } else {
                code = "Y";//停
                myHandler.sendEmptyMessage(3);
            }
        }
    }

    @Override
    public void onTouchDown() {
        isTouch = false;
        myHandler.removeMessages(2);

    }

}
